$("#mfilevurl").fileinput({
    dropZoneTitle : "请上传小于150M的视频！",
    showPreview: false,
    maxFileCount : 1,
    minFileCount:1,
    maxFileSize : 153600,//文件最大153600kb=150M
    showUpload: true,
    append:false,
    autoReplace : true,
    layoutTemplates : {
        actionUpload:'',
    },
    uploadLabel: "上传",removeLabel: "移除",language: "zh",
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/vfile?type=News&f=vurl',
    allowedFileExtensions : [ "mp4","avi","dat","3gp","mov","rmvb"],
    previewSettings : {
        image : {
            width : "100%",
            height : "100%"
        },
    }
}).on("fileuploaded", function (event, data) {
    console.log(data);
    $("#hidvurl").val(data.response.data);
})

$("#picmfile").fileinput({
    showPreview: true,
    showUpload: true,
    uploadLabel: "上传",removeLabel: "移除",language: "zh",
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=News&f=pic',
    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    if(atype="arowhead"){
        alist[ix].img=data.response.data
        alist[ix].hasdata=!0
        initNews(atype,alist)
    }else{
        mlist[ix].img=data.response.data
        mlist[ix].hasdata=!0
        initNews(atype,mlist)
    }
    // $("#picmfile").fileinput('refresh').fileinput('enable');
    $("#pic-form").modal('hide')
    lastatype = atype
    lastix = ix
})

function savewz() {
    console.log("======savewz")
    console.log("==================savewz val="+$("#info").val())
    console.log("==================ix="+ix)
    console.log("==================atype="+atype)
    if($("#info").val().length==0)return;

    if(atype=="arowhead"){
        alist[ix].wenzi=$("#info").val()
        alist[ix].hasdata=!0
        initNews(atype,alist)
    }else{
        mlist[ix].wenzi=$("#info").val()
        mlist[ix].hasdata=!0
        initNews(atype,mlist)
    }
    $("#weizi"+ix).val($("#info").val())
    $("#info").val("")
    $("#txt-form").modal('hide')
}

function savepic() {
    console.log("======savepic")
    $("#pic-form").modal('hide')
}

$("#photosmfile").fileinput({
    showPreview: true,
    showUpload: true,
    uploadLabel: "上传",removeLabel: "移除",language: "zh",
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=News&f=photos',
    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    $("#hidphotos").val(data.response.data);
})

function ncFormatter(id) {

}

function changeState(id, state) {
    $.ajax({
        type: 'POST',
        url: "changeState",
        data: {
            id: id,
            state: state
        },
        success: function () {
            $('#mytable').bootstrapTable('refresh', {url: '/admin/news/list'});
        },
        dataType: "json"
    });
}

function copypath(id) {
    swal({title: "操作成功", text: '/pages/newsdetail/newsdetail?duli=1&id='+id, type: "success"})
}

function guanlianSP(id,sid) {
    // swal({title: "操作成功", text: '/pages/newsdetail/newsdetail?duli=1&id='+id, type: "success"})

    console.log("===========id="+id)
    console.log("===========sid="+sid)
    $("#hidid").val(id)
    $("#hidsid").val(sid)
    $('#guanlianSP-form').modal("show");
    initnonestore(sid)
}

function initnonestore(sid) {
    $.ajax({
        //请求方式
        type : "get",
        //请求地址
        url : "getStoreGoods",
        //数据，json字符串
        data : {"sid":sid},
        //请求成功
        success : function(res) {
            console.log("===========================ajax result");
            console.log(res);
            $("#gsid").empty()
            $.each(res.data,function (index,item){
                $("#gid").append("<option value="+ item.id+">"+ item.name+"</option>");
            });
        },
        //请求失败，包含具体的错误信息
        error : function(e){
            console.log(e.status);
            console.log(e.responseText);
        }
    });
}

function guanlianSJSave() {
    var id =$("#hidid").val()
    var gid =$("#gid").val()
    console.log("===========guanlianSJSave id="+id)
    console.log("===========guanlianSJSave gid="+gid)

    $.ajax({
        type: 'POST',
        url: "guanliansp",
        data: {
            id: id,
            gid: gid
        },
        success: function (r) {
            console.log("=================guanlianSJSave post ok")
            swal({title: "操作成功", text: "", type: "success"})
            $('#guanlianSP-form').modal("hide");
            $('#mytable').bootstrapTable('refresh', {url: '/admin/news/list'});
        },
        dataType: "json"
    });
}

function actFormatter(value, row, index) {
    var state = row.state;
    var id = row.id;
    var sid = row.sid||'';
    var res = '<button data-toggle="modal" class="btn-sm btn-primary" href="list.html#modal-form" data-row=' + id + ' data-index=' + index + '>修改</button>';
    if (state == 1)
        res += ' <button type="button" class="btn-sm btn-info" onclick="changeState(\'' + id + '\',-1)" >禁用</button>';
    else
        res += ' <button typ-e="button" class="btn-sm btn-info" onclick="changeState(\'' + id + '\',1)" >启用</button>';
    res += ' <button typ-e="button" class="btn-sm btn-danger" onclick="deleteOne(\'' + id + '\')">删除</button>';
    res += ' <button typ-e="button" class="btn-sm btn-primary" onclick="copypath(\'' + id + '\')">复制路径</button>';
    res += ' <button typ-e="button" class="btn-sm btn-primary" onclick="guanlianSP(\'' + id + '\',\'' + sid + '\')">关联商品</button>';
    return res;
}

function deleteOne(id) {
    swal({
        title: '您确定要删除此行数据？',
        text: '你将无法恢复它！',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#ed5666',
        confirmButtonText: '确定删除！',
        cancelButtonText: '取消删除！',
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger',
        buttonsStyling: false
    }).then(function () {

        $.ajax({
            type: 'POST',
            url: "deleteOne",
            data: {
                id: id,
            },
            success: function (status) {
                if (status == 1) {
                    swal({title: "删除成功", text: "", type: "success"})
                    $('#mytable').bootstrapTable('refresh', {url: '/admin/news/list'});
                } else {
                    swal({title: "删除失败", text: "", type: "error"})
                }
            },
            dataType: "json"
        });

    }, function (dismiss) {
        // dismiss的值可以是'cancel', 'overlay',
        // 'close', 'timer'
        if (dismiss === 'cancel') {
            swal({title: '您已取消操作！', text: '', timer: 2000})
        }
    })
}

var editsw = [];

/**
 * 为模态框填充数据
 */
$('#modal-form').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget); // 触发事件的按钮
    var index = button.data('index');
    var modal = $(this);
    var data = $('#mytable').bootstrapTable("getData")[index]
    console.log(data)

    modal.find('#id').val(data.id)
    modal.find('#title').val(data.title)

    mlist = []
    if (data.info.indexOf('[{') == 0)
        mlist = JSON.parse(data.info)
    else {
        var photos = data.photos.split(';')
        for (var i = 0; i < photos.length; i++) {
            if (photos[i].length == 0) continue;
            if (i == 0) {
                mlist.push({wenzi: data.info, hasdata: !0, img: photos[i]})
            }
            else {
                mlist.push({wenzi: '', hasdata: !0, img: photos[i]})
            }
        }
    }
    atype = 'mrowhead'
    initNews('mrowhead', mlist)

    // 此部分需要注意：如果页面有两个以上的图片编辑
    // 该部分逻辑需要重写
    $("#mFile").fileinput('refresh', {
        initialPreview: [ //预览图片的设置
            "<img src='" + data.pic + "' class='file-preview-image' alt='' title=''>",
        ],
    });

    $("#mfilevurl2").fileinput('destroy');
    $("#mfilevurl2").fileinput({
        showPreview: false,
        showUpload: true,
        append: false,
        overwriteInitial:false,
        uploadClass: "btn btn-info",
        uploadLabel: "上传",removeLabel: "移除",language: "zh",
        uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
        initialPreviewShowDelete: true,
        initialPreviewAsData: true,
        // initialPreviewFileType: 'image',
        // initialPreview: getPreviewList(data.pic),
        previewFileIcon: '<i class="fa fa-file"></i>',
        // allowedPreviewTypes: ['image'],
        initialPreviewConfig: getPreviewConfig(data.pic, 'News', "vurl", data.id),
        elErrorContainer: '#kartik-file-errors',
        uploadUrl: '/admin/upload/vfile?type=News&f=vurl',
        allowedFileExtensions: ["mp4","rm","rmvb","mpeg1-4","mov","mtv","dat","wmv","avi","3gp","amv","dmv","flv"]
    }).on("fileuploaded", function (event, data) {
        console.log(data);
        $("#hidvurl2").val(data.response.data);
    }).on('filedeleted', function (event, key, jqXHR, data) {
        console.log('Key = ' + key);
        $("#hidvurl2").val('');
    })
    $("#hidvurl2").val(data.vurl)

    modal.find('#cid').find("option[value='" + data['cid'] + "']").attr("selected", true);

    editsw["state"] == undefined ? editsw["state"] = new Switchery(document.querySelector('#state'), {color: "#1AB394"}) : ""
    if (data.state == 1) {
        setSwitchery(editsw["state"], true);
    } else {
        setSwitchery(editsw["state"], false);
    }
    editsw["isTop"] == undefined ? editsw["isTop"] = new Switchery(document.querySelector('#isTop'), {color: "#1AB394"}) : ""
    if (data.isTop == 1) {
        setSwitchery(editsw["isTop"], true);
    } else {
        setSwitchery(editsw["isTop"], false);
    }
})

var alist = [{wenzi: "", hasdata: !1, img: ''}], mlist = [],atype="arowhead",ix=0,lastatype="arowhead",lastix=0

function upImg(acttype, i) {
    console.log("======upImg acttype=" + acttype)
    console.log("======upImg i=" + i)
    console.log("======upImg lastix=" + lastix)
    atype = acttype
    ix=i
    if (ix!=lastix) {
        $("#picmfile").fileinput('refresh').fileinput('enable');
        if (acttype == "arowhead"&&alist[i].img) {
            $("#picmfile").fileinput('refresh', {
                initialPreview: [ //预览图片的设置
                    "<img src='" + alist[i].img + "' class='file-preview-image' alt='' title=''>",
                ],
            });
        }
        if (acttype == "mrowhead"&&mlist[i].img) {
            $("#picmfile").fileinput('refresh', {
                initialPreview: [ //预览图片的设置
                    "<img src='" + mlist[i].img + "' class='file-preview-image' alt='' title=''>",
                ],
            });
        }
    }
    $("#pic-form").modal('show')
}

function wenzi(acttype,i) {
    console.log("======wenzi acttype=" + acttype)
    console.log("======wenzi i=" + i)
    atype = acttype
    ix=i
    $("#txt-form").modal('show')
    if (acttype == "arowhead") {
        $("#info").val(alist[i].wenzi)
    } else if (acttype == "mrowhead") {
        $("#info").val(mlist[i].wenzi)
    }
}

function createTuwen() {
    return {wenzi: "", hasdata: !1, img: ''};
}

function jian(acttype,idx) {
    console.log("======jian acttype=" + acttype)
    console.log("======jian idx=" + idx)

    var  tmp = [],fb_list=[]
    if (acttype == "arowhead") {
        fb_list = alist
    } else if (acttype == "mrowhead") {
        fb_list = mlist
    }

    for (var a = 0; a < fb_list.length; a++) {
        if (a != idx || fb_list.length == 1) {
            tmp.push(fb_list[a]);
        }
    }
    if (acttype == "arowhead") {
        alist=tmp
    } else if (acttype == "mrowhead") {
        mlist=tmp
    }
    initNews(acttype, tmp)
}

function jianews(acttype, idx) {
    console.log("======jianews acttype=" + acttype)
    console.log("======jianews idx=" + idx)
    var tmp = []

    if (acttype == "arowhead") {
        // alist.push({wenzi: "", hasdata: !1, img: ''})
        for (var a = 0; a < alist.length; a++) {
            if (a < idx) {
                tmp.push(alist[a]);
            } else if (a == idx) {
                tmp.push(alist[a]);
                tmp.push(createTuwen());
            } else {
                tmp.push(alist[a]);
            }
        }
        alist = tmp
    } else if (acttype == "mrowhead") {
        // mlist.push({wenzi: "", hasdata: !1, img: ''})
        for (var a = 0; a < mlist.length; a++) {
            if (a < idx) {
                tmp.push(mlist[a]);
            } else if (a == idx) {
                tmp.push(mlist[a]);
                tmp.push(createTuwen());
            } else {
                tmp.push(mlist[a]);
            }
        }
        mlist = tmp
    }
    initNews(acttype, tmp)
}

function initNews(acttype, list) {
    var neirong = "",cout = list.length
    console.log("======initNews acttype=" + acttype)
    console.log("======initNews list=" + list)
    console.log("======initNews cout=" + cout)
    if (acttype == "arowhead") {
        $("#arowhead").empty()
    } else if (acttype == "mrowhead") {
        $("#mrowhead").empty()
    }

    for (var i = 0; i < list.length; i++) {
        neirong = ""
        if (!list[i].hasdata) {
            neirong += "<div class='xuanze'><div class='xuanze-nr'><div  class='emitem' onclick='upImg(\"" + acttype + "\",\"" + i + "\")'><image src='/img/chuantu.png' style='width:100px;height:100px;margin: 10px;cursor:pointer'/></div>" +
                "<div class='emitem' onclick='wenzi(\"" + acttype + "\",\"" + i + "\")'><image src='/img/guantu.jpeg' style='width:100px;height:100px;margin: 10px;cursor:pointer'/></div></div>"
            if(cout>1)neirong += "<div class='guant' onclick='jian(\"" + acttype + "\",\"" + i +"\")'><image src='/img/x.png' style='width:18px;height:20px;border-radius: 50%;cursor:pointer'/></div>"
            neirong += "</div>"
        } else {
            neirong += "<div class='zhanshi-xg'>"
            if(cout>1)neirong += "<div class='guant' onclick='jian(\"" + acttype + "\",\"" + i + "\")'><image src='/img/x.png' style='width:18px;height:20px;border-radius: 50%;cursor:pointer'/></div>"

            if (list[i].img) {
                neirong += "<div class='zhanshi-tu' onclick='upImg(\"" + acttype + "\",\"" + i + "\")'><image src='" + list[i].img + "' style='width:100px;height:100px;margin: 10px;cursor:pointer'/></div>"
            } else {
                neirong += "<div class='zhanshi-tu' onclick='upImg(\"" + acttype + "\",\"" + i + "\")'><image src='/img/chuantu.png' style='width:100px;height:100px;margin: 10px;cursor:pointer'/></div>"
            }

            if (list[i].wenzi) {
                neirong += "<div class='wenzi' onclick='wenzi(\"" + acttype + "\",\"" + i + "\")'><textarea id='wenzi"+i+"' class='form-control' style='margin: 10px;width: 500px;height: 100px;overflow: hidden' readonly>" + list[i].wenzi + "</textarea></div>"
            } else {
                neirong += "<div class='wenzi' onclick='wenzi(\"" + acttype + "\",\"" + i + "\")'><image src='/img/guantu.jpeg' style='width:100px;height:100px;margin: 10px;cursor:pointer'/></div>"
            }
            neirong += "</div>"
        }
        neirong += "<div class='jia-jian'><div onclick='jianews(\"" + acttype + "\",\"" + i + "\")'><div class='jiatu'><image src='/img/jaitu.png' style='width:77px;height:15px;cursor:pointer'/></div></div></div>"
        if (acttype == "arowhead") {
            $("#arowhead").append(neirong)

        } else if (acttype == "mrowhead") {
            $("#mrowhead").append(neirong)
        }
    }

    console.log("======initNews over")

}

//tableHeight函数
function tableHeight() {
    //可以根据自己页面情况进行调整
    return $(window).height() - 200;
}

function sfglFormatter(value, row, index) {
    return value&&value > 0 ? "是" : "否";
}

function sfspFormatter(value, row, index) {
    return value&&value.length > 0 ? "是" : "否";
}

$(function () {

    var sw = [];
    $(".js-switch").each(function (i, e) {
        sw[i] = new Switchery(e, {color: "#1AB394"})
    })
    $(window).resize(function () {
        $('#mytable').bootstrapTable('resetView', {
            height: tableHeight()
        })
    })

    initNews("arowhead", alist)

    $("#auploadrow").hide()
    $("#muploadrow").hide()

    //生成用户数据
    $('#mytable').bootstrapTable({
        method: 'get',
        url: "/admin/news/list",
        // height:520,//高度调整
        // toolbar: '#toolbar',
        striped: true, //是否显示行间隔色
        dataField: "records",
        pagination: true,//是否分页
        queryParamsType: 'limit',
        queryParams: queryParams,
        sidePagination: 'server',
        pageNumber: 1, //初始化加载第一页，默认第一页
        pageSize: 50,//单页记录数
        pageList: [50, 100, 200, 500],//分页步进值
        showExport: true,//显示导出
        showRefresh: false,//刷新按钮
        showColumns: false,
        clikToSelect: true,//是否启用点击选中行
        // toolbarAlign:'right',
        // buttonsAlign:'right',//按钮对齐方式
        columns: [
            {
                title: '全选',
                field: 'select',
                checkbox: true,
                width: 25,
                align: 'center',
                valign: 'middle'
            },
            {
                title: 'ID',
                field: 'id',
                visible: false
            },
            {
                title: '标题',
                field: 'title'
            },
            {
                title: '引用图像',
                field: 'pic',
                formatter: "imgFormatter"
            },
            {
                title: '类别',
                field: 'cname'
            },
            {
                title: '是否置顶',
                field: 'isTop',
                formatter: "sfFormatter"
            },
            {
                title: '是否视频类',
                field: 'vurl',
                formatter: "sfspFormatter"
            },
            {
                title: '是否关联商品活动',
                field: 'gid',
                formatter: "sfglFormatter"
            },
            {
                title: '是否关联商品名字',
                field: 'gname'
            },
            {
                title: '启用状态',
                field: 'state',
                formatter: "stateFormatter"
            },
            {
                title: '操作',
                field: 'Attribute',
                align: 'center',
                width: 170,
                formatter: actFormatter
            }
        ],
        locale: 'zh-CN',//中文支持,
    })

    //请求服务数据时所传参数
    function queryParams(params) {
        var p = {
            limit: params.limit,
            offset: params.offset,
            sort: params.sort,
            order: params.order
            , search: $('#search').val()
            , ncategory: $('#ncategory').val()
        }
        return p;
    }

    $('#search_btn').click(function () {
        $('#mytable').bootstrapTable('refresh');
    })

    /*
     * 验证错误提示信息高亮
     */
    $.validator.setDefaults({
        highlight: function (e) {
            $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
        }, success: function (e) {
            e.closest(".form-group").removeClass("has-error").addClass("has-success")
        }, errorElement: "span", errorPlacement: function (e, r) {
            e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
        }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
    }), $("#aform").validate(), $("#mform").validate();
})

function checkAdd() {
    $('#ainfo').val(JSON.stringify(alist))
    var pic=""
    for (var a = 0; a < alist.length; a++) {
       if(alist[a].img){
           pic= alist[a].img
           break;
       }
    }
    if(!pic){
        swal({title: "请至少传一张图片", text: "", type: "error"})
        return false;
    }
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("name") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("name") + "=" + $(this).val())
        }
    });

    // $('#info').val($('#sninfo').code())
    // if ($("#hidpic").attr("required") == "required"
    //     && $("#hidpic").val() == "") {
    //     swal({title: "请上传图片", text: "", type: "warning"})
    //     return false;
    // }
    $('#apic').val(pic)
    $('#ainfo').val(JSON.stringify(alist))
    return true;
}

function checkModify() {
    $('#minfo').val(JSON.stringify(mlist))
    var pic=""
    for (var a = 0; a < mlist.length; a++) {
        if(mlist[a].img){
            pic= mlist[a].img
            break;
        }
    }
    if(!pic){
        swal({title: "请至少传一张图片", text: "", type: "error"})
        return false;
    }

    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("id") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("id") + "=" + $(this).val())
        }
    });

    // $('#info2').val($('#sninfo2').code())
    // if ($("#hidpic2").attr("required") == "required"
    //     && $("#hidpic2").val() == "") {
    //     swal({title: "请上传图片", text: "", type: "warning"})
    //     return false;
    // }
    $('#mpic').val(pic)
    $('#minfo').val(JSON.stringify(mlist))
    return true;
}